package com.canal.display.controller;

import com.canal.display.entity.canal.ZcolChannel;
import com.canal.display.exception.BuzException;
import com.canal.display.response.Result;
import com.canal.display.response.ResultUtil;
import com.canal.display.service.ZcolChannelService;
import com.canal.display.transfer.req.RecordConditions;
import com.canal.display.transfer.req.RestPwdReq;
import com.canal.display.transfer.resp.UserResp;
import com.canal.display.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author yangbo
 * @Date 2019-03-18 14:43
 */
@RestController
public class UserController {

    @Autowired
    private ZcolChannelService channelService;

    @Autowired
    private ZcolChannelService zcolChannelService;

    /**
     * 用户基本信息
     * @return
     */
    @GetMapping(value = "/info")
    @PreAuthorize("isAuthenticated()")
    public Result userInfo() {
        ZcolChannel sysUser = SecurityUtils.currentUser();
        UserResp userResp = new UserResp();
        userResp.setName(sysUser.getName());
        userResp.setAvatar("https://avatars1.githubusercontent.com/u/17971463?s=60&v=4");
        return ResultUtil.makeSuccess(userResp);
    }

    /**
     * 渠道商每天的跑量
     * @param conditions
     * @return
     */
    @PostMapping(value = "/dashboard")
    @PreAuthorize("isAuthenticated()")
    public Result dashboard(@RequestBody RecordConditions conditions) throws BuzException {
        return ResultUtil.makeSuccess(channelService.recordList(conditions));
    }

    /**
     * 修改密码
     * @param req
     * @param bindingResult
     * @return
     * @throws BuzException
     */
    @PostMapping(value = "/up/pwd")
    @PreAuthorize("isAuthenticated()")
    public Result updatePwd(@RequestBody @Validated RestPwdReq req,
                            BindingResult bindingResult) throws BuzException {
        if(bindingResult.hasErrors()) {
            throw new BuzException(400,bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        ZcolChannel zcolChannel = SecurityUtils.currentUser();
        if(zcolChannel == null) {
            throw new BuzException(403,"用户未登录");
        }
        zcolChannelService.updatePwd(req,zcolChannel.getId());
        return ResultUtil.makeSuccess("修改密码成功");
    }

}
